﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Telerik.WinControls.UI;
using Zvezda.FSO2.DB;
using Zvezda.FSO2.DB.DataSetFSOTableAdapters;

namespace FSO
{
    public partial class FormVatInvoice : Form, InterfaceObjDeleteableForm
    {
        private DataSetFSO.VAT_INVOICERow _vatInvRow;

        //Элементы для выпадающих списков
        //Для вида Счет фактуры
        RadListDataItem _productType = new RadListDataItem() { Text = "Товары/Работы", Value = "Товары/Работы" };
        RadListDataItem _serviceType = new RadListDataItem() { Text = "Услуги", Value = "Услуги" };
        //Для типа отгрузки
        RadListDataItem _tnnExec = new RadListDataItem() { Text = "ТТН", Value = "ТТН" };
        RadListDataItem _actExec = new RadListDataItem() { Text = "Акт выполнения", Value = "Акт выполнения" };
		public bool AllowSave;
        
        public FormVatInvoice(int? pid)
        {
            InitializeComponent();

            _vatInvRow = dataSetFSO1.VAT_INVOICE.NewVAT_INVOICERow();

            //Полю "Дата" по умолчанию присваиваем сегодняшнее число
            _vatInvRow.DATE = DateTime.Now.Date;

            if (pid == null)
            {
                //Может это будут с-ф за услуги
                _vatInvRow.TYPE = (string) _serviceType.Value;
                _vatInvRow.IS_GUARANTY_LET = false;
            }
            else
            {
                CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();

                _vatInvRow.PID = pid.Value;
                
                //По умолчанию с-ф выписывается не по гарантийному письму
                _vatInvRow.IS_GUARANTY_LET = false;
                //Это Счет фактура за товары/работы
                _vatInvRow.TYPE = (string) _productType.Value;
                //Вид отгрузки - ТТН
                _vatInvRow.EXEC_TYPE = (string)_tnnExec.Value;
                //по умолчанию присваиваем организацию из договора
                int orgId = taContract.GetDataByPID(_vatInvRow.PID).First().NSI_ORGANIZATION_ID;
                if (orgId > 0)
                {
                    _vatInvRow.NSI_ORGANIZATION_ID = orgId;
                }
            }
            dataSetFSO1.VAT_INVOICE.AddVAT_INVOICERow(_vatInvRow);
        }

        public FormVatInvoice(DataSetFSO.VAT_INVOICERow row)
        {
            InitializeComponent();

            vaT_INVOICETableAdapter1.FillByID(dataSetFSO1.VAT_INVOICE, row.ID);
            _vatInvRow = dataSetFSO1.VAT_INVOICE.FindByID(row.ID);

            this.Text = "Счет фактура № " + _vatInvRow.NUMBER;
        }

        public int Delete()
        {
            _vatInvRow.Delete();
            vaT_INVOICETableAdapter1.Update(_vatInvRow);
            this.Close();

            return 0;
        }

        public int Save()
        {
            int returnValue = -1;

            if (_vatInvRow.IsNUMBERNull())
            {
                MessageBox.Show(this, "Не заполнено обязательное поле \"Номер\".\nИзменения не будут сохранены", "Обязательное поле", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                vaT_INVOICETableAdapter1.Update(_vatInvRow);

                if (_vatInvRow.TYPE == (string)_productType.Value)
                {
                    #region Сохранение сф за продукцию
                    
                    PRODUCT_UNITTableAdapter taPU = new PRODUCT_UNITTableAdapter();

                    foreach (DataSetFSO.VIEW_VAT_IVOICE_ITEMRow row in dataSetFSO1.VIEW_VAT_IVOICE_ITEM.Rows)
                    {
                        DataSetFSO.PRODUCT_UNITRow productUnitRow;
                        if (row.RowState == DataRowState.Added)
                        {
                            productUnitRow = taPU.GetDataByID(row.ID).FindByID(row.ID);
                            productUnitRow.VAT_INVOICE_ID = _vatInvRow.ID;

                            taPU.Update(productUnitRow);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            //Получаем данные удаленной строки из оригинальной версии (до удаления)
                            int rowId = (int)row[dataSetFSO1.VIEW_VAT_IVOICE_ITEM.IDColumn, DataRowVersion.Original];

                            productUnitRow = taPU.GetDataByID(rowId).FindByID(rowId);
                            productUnitRow.SetVAT_INVOICE_IDNull();

                            taPU.Update(productUnitRow);
                        }
                    }
                    #endregion
                }
                else if (_vatInvRow.TYPE == (string)_serviceType.Value)
                {
                    #region Сохранение сф за услуги
                    VAT_INV_ON_SERVICETableAdapter ta = new VAT_INV_ON_SERVICETableAdapter();

                    foreach (DataSetFSO.VIEW_VAT_INV_ON_SERVICERow row in dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.Rows)
                    {
                        DataSetFSO.VAT_INV_ON_SERVICERow vatInvOnServRow;
                        if (row.RowState == DataRowState.Added)
                        {
                            vatInvOnServRow = dataSetFSO1.VAT_INV_ON_SERVICE.NewVAT_INV_ON_SERVICERow();
                            vatInvOnServRow.VAT_INVOICE_ID = _vatInvRow.ID;
                            vatInvOnServRow.NSI_SERVICE_ID = row.NSI_SERVICE_ID;
                            //payInOnServRow.PID = _payInRow.PID;
                            vatInvOnServRow.QUANTITY = row.QUANTITY;

                            dataSetFSO1.VAT_INV_ON_SERVICE.AddVAT_INV_ON_SERVICERow(vatInvOnServRow);

                            ta.Update(vatInvOnServRow);
                        }
                        else if (row.RowState == DataRowState.Modified)
                        {
                            vatInvOnServRow = ta.GetDataByID(row.ID).FindByID(row.ID);
                            vatInvOnServRow.QUANTITY = row.QUANTITY;

                            ta.Update(vatInvOnServRow);
                        }
                        else if (row.RowState == DataRowState.Deleted)
                        {
                            //Получаем данные удаленной строки из оригинальной версии (до удаления)
                            int rowId = (int)row[dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.IDColumn, DataRowVersion.Original];
                            vatInvOnServRow = ta.GetDataByID(rowId).FindByID(rowId);
                            vatInvOnServRow.Delete();

                            ta.Update(vatInvOnServRow);
                        }
                    }
                    #endregion
                }
                RefreshForm();
                returnValue = 0;
            }

            return returnValue;
        }

        public int RefreshForm()
        {

            //Очищаем все таблицы
            foreach (DataTable table in dataSetFSO1.Tables)
            {
                if (!(table is DataSetFSO.VAT_INVOICEDataTable))
                {
                    table.Clear();
                }
            }

            //Заполняем постоянные для конкретной с-ф поля формы

            CONTRACTTableAdapter taContract = new CONTRACTTableAdapter();
            NSI_ORGANIZATIONTableAdapter taOrg = new NSI_ORGANIZATIONTableAdapter();
            NSI_TYPE_OF_ACTIVITYTableAdapter taTypeOfAct = new NSI_TYPE_OF_ACTIVITYTableAdapter();

            if (_vatInvRow.TYPE == (string)_productType.Value)
            {
                #region Обновление для обычной сф
                //Находим контракт, в рамках которого создан платеж
                DataSetFSO.CONTRACTRow contract = taContract.GetDataByPID(_vatInvRow.PID).First();
                radLabelContract.Text = contract.NUMBER;

                if (!_vatInvRow.IsNSI_ORGANIZATION_IDNull())
                {
                    radLabelOrganization.Text = taOrg.GetDataById(_vatInvRow.NSI_ORGANIZATION_ID).FindByID(_vatInvRow.NSI_ORGANIZATION_ID).SHORT_NAME;
                }
                else
                {
                    radLabelOrganization.Text = "<Не указана>";
                }

                if (!contract.IsNSI_TYPE_OF_ACTIVITY_IDNull())
                {
                    radLabelTypeOfAct.Text = taTypeOfAct.GetData().FindByID(contract.NSI_TYPE_OF_ACTIVITY_ID).NAME;
                }
                else
                {
                    radLabelTypeOfAct.Text = "<Не указано>";
                }

                //заполняем таблицу товаров
                vieW_VAT_IVOICE_ITEMTableAdapter1.FillByID(dataSetFSO1.VIEW_VAT_IVOICE_ITEM, _vatInvRow.ID);
                //Заполняем связанные счета
                VIEW_SEARCH_INVOICE_OUTTableAdapter taInvOut = new VIEW_SEARCH_INVOICE_OUTTableAdapter();
                taInvOut.FillByVatInvID(dataSetFSO1.VIEW_SEARCH_INVOICE_OUT, _vatInvRow.ID);
                userControlSearchInvoiceOut1.OwnerDataSet = dataSetFSO1;
                //Заполняем связанные платежи
                VIEW_SEARCH_PAYMENT_INTableAdapter taPayIn = new VIEW_SEARCH_PAYMENT_INTableAdapter();
                taPayIn.FillByVatInvID(dataSetFSO1.VIEW_SEARCH_PAYMENT_IN, _vatInvRow.ID);
                userControlSearchPaymentIn1.OwnerDataSet = dataSetFSO1;

                BindControls();
                InitializeProductsGrid();

                EvaluateRest();

                #endregion
            }
            else if (_vatInvRow.TYPE == (string)_serviceType.Value)
            {
                #region Обновление сф по услугам

                if (!_vatInvRow.IsNSI_ORGANIZATION_IDNull())
                {
                    radLabelOrganization.Text = taOrg.GetDataById(_vatInvRow.NSI_ORGANIZATION_ID).FindByID(_vatInvRow.NSI_ORGANIZATION_ID).SHORT_NAME;
                }
                else
                {
                    radLabelOrganization.Text = "<Не указана>";
                }

                //Заполняем пункты счет фактуры по услугам
                vieW_VAT_INV_ON_SERVICETableAdapter1.FillByVatID(dataSetFSO1.VIEW_VAT_INV_ON_SERVICE, _vatInvRow.ID);

                BindControls();
                InitializeServiceGrid();
                #endregion
            }
            
            return 0;
        }

        public string FormName
        {
            get
            {
                string returnString = "VAT_INVOICE_";

                if (_vatInvRow.ID <= 0)
                {
                    returnString = returnString + DateTime.Now;
                }
                else
                {
                    returnString = returnString + _vatInvRow.ID;
                }

                return returnString;
            }
        }

        private void BindControls()
        {
            //Номер
            radTextBoxNumber.DataBindings.Clear();
            radTextBoxNumber.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Дата
            radDateTimePickerDate.DataBindings.Clear();
            radDateTimePickerDate.DataBindings.Add("Value", _vatInvRow, dataSetFSO1.VAT_INVOICE.DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Сумма 
            radMaskedEditBoxSum.DataBindings.Clear();
            radMaskedEditBoxSum.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.SUM_RUBColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged, 0, "N2");


            ////Тип с-ф
            //radDropDownListType.DataBindings.Clear();
            //radDropDownListType.DataBindings.Add("SelectedValue", _vatInvRow, dataSetFSO1.VAT_INVOICE.TYPEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            ////Тип отгрузки
            //radDropDownListExecType.DataBindings.Clear();
            //radDropDownListExecType.DataBindings.Add("SelectedValue", _vatInvRow, dataSetFSO1.VAT_INVOICE.EXEC_TYPEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //номер акта или ttn
            radTextBoxExecNumber.DataBindings.Clear();
            radTextBoxExecNumber.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.EXEC_NUMBERColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);


            //по гп или нет
            radCheckBoxIsGuarantyLet.DataBindings.Clear();
            radCheckBoxIsGuarantyLet.DataBindings.Add("Checked", _vatInvRow, dataSetFSO1.VAT_INVOICE.IS_GUARANTY_LETColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Дата ГП
            radTextBoxGLetterDate.DataBindings.Clear();
            radTextBoxGLetterDate.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.GUARANTY_LET_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            //radDateTimePickerGLetterDate.DataBindings.Clear();
            //radDateTimePickerGLetterDate.DataBindings.Add("Value", _vatInvRow, dataSetFSO1.VAT_INVOICE.GUARANTY_LET_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Комментарии
            radTextBoxDescription.DataBindings.Clear();
            radTextBoxDescription.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.DESCRIPTIONColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);

            //Счет на доплату
            radTextBoxInvPayAddNum.DataBindings.Clear();
            radTextBoxInvPayAddNum.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.INVOICE_OF_PAY_ADD_NUMColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            
        }

        private void FormVatInvoice_Load(object sender, EventArgs e)
        {
            if (_vatInvRow.TYPE == (string)_productType.Value)
            {
                dataSetFSO1.VIEW_VAT_IVOICE_ITEM.RowChanged += new DataRowChangeEventHandler(VIEW_VAT_IVOICE_ITEM_RowChanged);

                dataSetFSO1.AGGR_PRODUCT_UNTS.RowChanged += new DataRowChangeEventHandler(AGGR_PRODUCT_UNTS_RowChanged);

                if (_vatInvRow.IS_GUARANTY_LET)
                {
                    radTextBoxGLetterDate.Visible = true;
                }
                else
                {
                    radTextBoxGLetterDate.Visible = false;
                }

                ////Тип сф
                //radDropDownListType.Items.Clear();
                //radDropDownListType.Items.Add(_productType);
                //radDropDownListType.Items.Add(_serviceType);

                //Тип отгрузки
                //radDropDownListExecType.Items.Clear();
                //radDropDownListExecType.Items.Add(_tnnExec);
                //radDropDownListExecType.Items.Add(_actExec);

                if (_vatInvRow.EXEC_TYPE == (string) _tnnExec.Value)
                {
                    radRadioButtonTNN.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On;
                }
                else
                {
                    radRadioButtonAct.ToggleState = Telerik.WinControls.Enumerations.ToggleState.On;
                }

                radGridViewItems.MultiSelect = true;


            }else if(_vatInvRow.TYPE == (string) _serviceType.Value)
            {
                if (_vatInvRow.IS_GUARANTY_LET)
                {
                    radTextBoxGLetterDate.Visible = true;
                }
                else
                {
                    radTextBoxGLetterDate.Visible = false;
                }

                //radDropDownListExecType.Enabled = false;
                radTextBoxExecNumber.Enabled = false;
                radRadioButtonAct.Enabled = false;
                radRadioButtonTNN.Enabled = false;
                radDropDownButtonAddFrom.Visible = false;
                radGroupBoxInvOut.Visible = false;
                radGroupBoxPayIn.Visible = false;
                panelRest.Visible = false;
                radButtonEvaluateSum.Visible = false;

                radGridViewItems.MultiSelect = true;
            }

            radGridViewItems.MasterTemplate.EnableGrouping = false;

            RefreshForm();
        }

        #region Работа с агрегированной таблицей
        private void radGridViewItems_UserDeletingRow(object sender, GridViewRowCancelEventArgs e)
        {
            PRODUCT_UNITTableAdapter taPU = new PRODUCT_UNITTableAdapter();
            foreach (GridViewRowInfo ri in e.Rows)
            {
                if (ri != null && ri.DataBoundItem != null && (ri.DataBoundItem as DataRowView).Row is DataSetFSO.VIEW_VAT_IVOICE_ITEMRow)
                {
                    DataSetFSO.VIEW_VAT_IVOICE_ITEMRow vatItemRow = (ri.DataBoundItem as DataRowView).Row as DataSetFSO.VIEW_VAT_IVOICE_ITEMRow;

                    DataSetFSO.AGGR_PRODUCT_UNTSRow aggrPayRow = (from aggrRow in dataSetFSO1.AGGR_PRODUCT_UNTS where (aggrRow.NSI_PRODUCT_ID == vatItemRow.NSI_PRODUCT_ID) select aggrRow).First();
                    aggrPayRow.COUNT--;

                }
            }
        }

        void AGGR_PRODUCT_UNTS_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change)
            {
                //MessageBox.Show(e.Action.ToString());
                DataSetFSO.AGGR_PRODUCT_UNTSRow aggrProductRow = e.Row as DataSetFSO.AGGR_PRODUCT_UNTSRow;
                //Выбираем строку грида (не датасета) по заданному NSI_PRODUCT_ID
                GridViewRowInfo rowInfo = (from rInf in radGridViewItems.MasterTemplate.Rows where ((int)rInf.Cells[dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_PRODUCT_IDColumn.ColumnName].Value == aggrProductRow.NSI_PRODUCT_ID) select rInf).FirstOrDefault();
                if (rowInfo != null)
                {
                    if (aggrProductRow.COUNT < 1)
                    {
                        rowInfo.IsVisible = false;
                    }
                    else
                    {
                        rowInfo.IsVisible = true;
                    }
                }
            }
        }

        void VIEW_VAT_IVOICE_ITEM_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Add)
            {
                //MessageBox.Show("Добавляемся!!!");
                DataSetFSO.VIEW_VAT_IVOICE_ITEMRow rowVatItem = e.Row as DataSetFSO.VIEW_VAT_IVOICE_ITEMRow;

                DataSetFSO.AGGR_PRODUCT_UNTSRow aggrProductRow = (from aggrRow in dataSetFSO1.AGGR_PRODUCT_UNTS where (aggrRow.NSI_PRODUCT_ID == rowVatItem.NSI_PRODUCT_ID) select aggrRow).FirstOrDefault();
                //Если такой записи нет а аггрегированной таблице
                if (aggrProductRow == null)
                {
                    aggrProductRow = dataSetFSO1.AGGR_PRODUCT_UNTS.NewAGGR_PRODUCT_UNTSRow();
                    aggrProductRow.NSI_METER_NAME = rowVatItem.NSI_METER_NAME;
                    aggrProductRow.NSI_PRODUCT_ID = rowVatItem.NSI_PRODUCT_ID;
                    if (rowVatItem.NSI_PRODUCT_ID == -1)
                    {
                        //значит данный товар - работа
                        aggrProductRow.PRODUCT_UNIT_NAME = "Работы";
                    }
                    else
                    {
                        aggrProductRow.PRODUCT_UNIT_NAME = rowVatItem.PRODUCT_UNIT_NAME;
                    }
                    dataSetFSO1.AGGR_PRODUCT_UNTS.AddAGGR_PRODUCT_UNTSRow(aggrProductRow);
                }
                aggrProductRow.COUNT++;
            }
            else if (e.Action == DataRowAction.Nothing)
            {
                MessageBox.Show("Удаляемся!!");
            }
        }
        #endregion

        private void InitializeProductsGrid()
        {
            //Колонки для агрегированной таблицы


            //Название товара
            GridViewTextBoxColumn colProdName = new GridViewTextBoxColumn("AGGR_PRODUCT_NAME", dataSetFSO1.AGGR_PRODUCT_UNTS.PRODUCT_UNIT_NAMEColumn.ColumnName);
            colProdName.HeaderText = "Имя";
            colProdName.ReadOnly = true;

            //Количество товара
            GridViewTextBoxColumn colCount = new GridViewTextBoxColumn("AGGR_COUNT", dataSetFSO1.AGGR_PRODUCT_UNTS.COUNTColumn.ColumnName);
            colCount.HeaderText = "Кол.";
            colCount.ReadOnly = true;

            //Единица измерения
            GridViewTextBoxColumn colAggrNSIMeter = new GridViewTextBoxColumn("AGGR_NSI_METER", dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_METER_NAMEColumn.ColumnName);
            colAggrNSIMeter.HeaderText = "ед.";
            colAggrNSIMeter.ReadOnly = true;

            //соединительная колонка
            GridViewTextBoxColumn colNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_PRODUCT_IDColumn.ColumnName);
            colNSIProdId.IsVisible = false;
            colNSIProdId.VisibleInColumnChooser = false;

            radGridViewItems.MasterTemplate.Columns.Clear();
            radGridViewItems.MasterTemplate.Columns.Add(colProdName);
            radGridViewItems.MasterTemplate.Columns.Add(colNSIProdId);
            radGridViewItems.MasterTemplate.Columns.Add(colCount);
            radGridViewItems.MasterTemplate.Columns.Add(colAggrNSIMeter);

            radGridViewItems.MasterTemplate.AllowAddNewRow = false;
            radGridViewItems.MasterTemplate.AllowDeleteRow = false;

            radGridViewItems.MasterTemplate.DataSource = dataSetFSO1.AGGR_PRODUCT_UNTS;


            //Таблица для единиц товара
            GridViewTemplate PUTemplate = new GridViewTemplate();

			//календарный план
			GridViewTextBoxColumn colCalendarPlan = new GridViewTextBoxColumn("PU_CALENDAR_PLAN", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.CALENDAR_PLAN_NUMBERColumn.ColumnName);
			colCalendarPlan.HeaderText = "Календарный план";
			colCalendarPlan.ReadOnly = true;

            GridViewTextBoxColumn colPUName = new GridViewTextBoxColumn("PU_NAME", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.PRODUCT_UNIT_NAMEColumn.ColumnName);
            colPUName.HeaderText = "Наименование";
            colPUName.ReadOnly = true;

            //Цена товара
            GridViewDecimalColumn colPUCost = new GridViewDecimalColumn("PU_Cost", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.PRODUCT_UNIT_COSTColumn.ColumnName);
            colPUCost.HeaderText = "Цена";
            colPUCost.FormatString = "{0:N2}";

            //Валюта
            GridViewTextBoxColumn colPUCurName = new GridViewTextBoxColumn("PU_CURRENCY_NAME", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.NSI_CURRENCY_NAMEColumn.ColumnName);
            colPUCurName.HeaderText = "Вал.";
            colPUCurName.ReadOnly = true;


            // % оплаты
            GridViewDecimalColumn colPUPerPay = new GridViewDecimalColumn("PU_PER_PAY", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.PAY_PERColumn.ColumnName);
            colPUPerPay.HeaderText = "% оплаты";
            colPUPerPay.FormatString = "{0:N2}%";

            //Конец этапа
            GridViewDateTimeColumn colPUCPEndDate = new GridViewDateTimeColumn("PU_CP_END_DATE", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.CP_STAGE_END_DATEColumn.ColumnName);
            colPUCPEndDate.HeaderText = "Отгрузка";
            colPUCPEndDate.FormatString = "{0:d}";

            //№ счет-фактуры
            GridViewTextBoxColumn colVatInvNum = new GridViewTextBoxColumn("PU_VAT_INV_NUM", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.VAT_INVOICE_NUMBERColumn.ColumnName);
            colVatInvNum.HeaderText = "№ С-Ф";
            colVatInvNum.ReadOnly = true;

            //Дата счет-фактуры
            GridViewTextBoxColumn colVatInvDate = new GridViewTextBoxColumn("PU_VAT_INVOICE_DATE", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.VAT_INVOICE_DATE1Column.ColumnName);
            colVatInvDate.HeaderText = "Дата С-Ф";
            colVatInvDate.ReadOnly = true;
            //colVatInvDate.FormatString = "{0:d}";

            //№ счета
			GridViewTextBoxColumn colInvOutNum = new GridViewTextBoxColumn("PU_INVOICE_OUT_NUMBER", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.INVOICE_OUT_NUMBERColumn.ColumnName);
			colInvOutNum.HeaderText = "№ счета";
			colInvOutNum.ReadOnly = true;

            ////Дата платежа
            //GridViewTextBoxColumn colPayInDate = new GridViewTextBoxColumn("PU_PAYMENT_IN_ITEM_DATE", dataSetFSO1.VIEW_INV_OUT_ITEM.PAYMENT_IN_ITEM_DATEColumn.ColumnName);
            //colPayInDate.HeaderText = "Дата платежа";
            //colPayInDate.ReadOnly = true;

			//номер чертежа
			GridViewTextBoxColumn colDrawing = new GridViewTextBoxColumn("PU_N_DRAWING", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.N_DRAWINGColumn.ColumnName);
			colDrawing.HeaderText = "№ чертежа";
			colDrawing.ReadOnly = true;


            //Статус изделия
            GridViewTextBoxColumn colProductState = new GridViewTextBoxColumn("PU_NSI_PRODUCT_STATE_NAME", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.NSI_PRODUCT_STATE_NAMEColumn.ColumnName);
            colProductState.HeaderText = "Статус изделия";
            colProductState.ReadOnly = true;

            //Группа товара
			GridViewTextBoxColumn colProductGroup = new GridViewTextBoxColumn("PU_PROD_GROUP", dataSetFSO1.VIEW_VAT_IVOICE_ITEM.NSI_PROD_GROUP_NAMEColumn.ColumnName);
            colProductGroup.HeaderText = "Группа товара";
            colProductGroup.ReadOnly = true;

            //Соединительное поле
            GridViewTextBoxColumn colPUNSIProdId = new GridViewTextBoxColumn(dataSetFSO1.VIEW_VAT_IVOICE_ITEM.NSI_PRODUCT_IDColumn.ColumnName);
            colPUNSIProdId.IsVisible = false;
            colPUNSIProdId.VisibleInColumnChooser = false;

            PUTemplate.Columns.Clear();
			PUTemplate.Columns.Add(colCalendarPlan);
            PUTemplate.Columns.Add(colPUName);
            PUTemplate.Columns.Add(colPUCost);
            PUTemplate.Columns.Add(colPUCurName);
            PUTemplate.Columns.Add(colPUPerPay);
            PUTemplate.Columns.Add(colPUCPEndDate);
            PUTemplate.Columns.Add(colPUNSIProdId);
            PUTemplate.Columns.Add(colVatInvNum);
            PUTemplate.Columns.Add(colVatInvDate);
            PUTemplate.Columns.Add(colInvOutNum);
            //PUTemplate.Columns.Add(colPayInDate);
			PUTemplate.Columns.Add(colDrawing);
            PUTemplate.Columns.Add(colProductState);
            PUTemplate.Columns.Add(colProductGroup);
            PUTemplate.DataSource = dataSetFSO1.VIEW_VAT_IVOICE_ITEM;
            PUTemplate.ShowFilteringRow = false;
            PUTemplate.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
            PUTemplate.AllowAddNewRow = false;
            PUTemplate.AllowDeleteRow = false;
            PUTemplate.ReadOnly = true;

            radGridViewItems.Templates.Clear();
            radGridViewItems.Templates.Add(PUTemplate);

            GridViewRelation relation = new GridViewRelation(radGridViewItems.MasterTemplate, PUTemplate);
            relation.ParentColumnNames.Add(dataSetFSO1.AGGR_PRODUCT_UNTS.NSI_PRODUCT_IDColumn.ColumnName);
            relation.ChildColumnNames.Add(dataSetFSO1.VIEW_VAT_IVOICE_ITEM.NSI_PRODUCT_IDColumn.ColumnName);

            radGridViewItems.Relations.Clear();
            radGridViewItems.Relations.Add(relation);
        }

        private void InitializeServiceGrid()
        {
            GridViewTextBoxColumn colServName = new GridViewTextBoxColumn("SERVICE_NAME", dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.NSI_SERVICE_NAMEColumn.ColumnName);
            colServName.HeaderText = "Наименование";
            colServName.ReadOnly = true;

            GridViewDecimalColumn colCount = new GridViewDecimalColumn("COUNT", dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.QUANTITYColumn.ColumnName);
            colCount.HeaderText = "Кол.";
            colCount.FormatString = "{0:N2}";
            //colCount.DecimalPlaces = 0;
            colCount.Minimum = 0;

            GridViewTextBoxColumn colMeter = new GridViewTextBoxColumn("NSI_METER_NAME", dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.NSI_METER_NAMEColumn.ColumnName);
            colMeter.HeaderText = "Ед.";
            colMeter.ReadOnly = true;

            radGridViewItems.MasterTemplate.Columns.Clear();
            radGridViewItems.MasterTemplate.Columns.Add(colServName);
            radGridViewItems.MasterTemplate.Columns.Add(colCount);
            radGridViewItems.MasterTemplate.Columns.Add(colMeter);

            radGridViewItems.AllowAddNewRow = false;
            radGridViewItems.AllowDeleteRow = false;
            radGridViewItems.AllowDragToGroup = false;
            radGridViewItems.ShowGroupPanel = false;
            radGridViewItems.EnableGrouping = false;

            radGridViewItems.DataSource = dataSetFSO1.VIEW_VAT_INV_ON_SERVICE;
        }

        private void radButtonAddProducts_Click(object sender, EventArgs e)
        {
            if (_vatInvRow.TYPE == (string)_productType.Value)
            {
                #region Добавление продукции
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _vatInvRow.PID);
                //Заполняем только теми товарами цена на которые указана в валюте счета
                if (_vatInvRow.IS_GUARANTY_LET)
                {
                    (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridForVatInvoice(_vatInvRow.PID);
                }
                else
                {
                    (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridForVatInvoiceNotGLet(_vatInvRow.PID);
                }
                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }
                #endregion
            }
            else if (_vatInvRow.TYPE == (string)_serviceType.Value)
            {
                #region Добавление услуг
                DialogFormSelectObject selectServiceDialog = new DialogFormSelectObject(ObjctTypeEnum.NSI_SERVICE);
                if (selectServiceDialog.ShowDialog() == DialogResult.OK)
                {
                    //selectPUDialog.SelectedRows
                    foreach (GridViewRowInfo rowInf in selectServiceDialog.SelectedRows)
                    {
                        DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                        if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_NSI_SERVICERow)
                        {
                            DataSetFSO.VIEW_SEARCH_NSI_SERVICERow serviceRow = drv.Row as DataSetFSO.VIEW_SEARCH_NSI_SERVICERow;

                            try
                            {
                                DataSetFSO.VIEW_VAT_INV_ON_SERVICERow rowVatInvOnServ = dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.NewVIEW_VAT_INV_ON_SERVICERow();

                                rowVatInvOnServ.VAT_INVOICE_ID = _vatInvRow.ID;
                                rowVatInvOnServ.NSI_SERVICE_ID = serviceRow.ID;

                                rowVatInvOnServ.NSI_SERVICE_NAME = serviceRow.SHORT_NAME;
                                rowVatInvOnServ.QUANTITY = serviceRow.COUNT;
                                rowVatInvOnServ.NSI_METER_NAME = serviceRow.NSI_METER_NAME;


                                dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.AddVIEW_VAT_INV_ON_SERVICERow(rowVatInvOnServ);

                                ////Изменяем аггрегированную таблицу


                            }
                            catch (ConstraintException)
                            {
                                MessageBox.Show("Данная услуга уже добавлена к счет-фактуре!");
                            }
                        }
                    }
                }
                #endregion
            }
        }
        //Добавление товаров
        private void AddPUFromSelectDialog(DialogFormSelectObject selectPUDialog)
        {
            foreach (GridViewRowInfo rowInf in selectPUDialog.SelectedRows)
            {
                DataRowView drv = (DataRowView)rowInf.DataBoundItem;
                if (drv != null && drv.Row is DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow)
                {
                    DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow productUnitRow = drv.Row as DataSetFSO.VIEW_SEARCH_P_U_FOR_FORMSRow;

                    try
                    {
                        DataSetFSO.VIEW_VAT_IVOICE_ITEMRow rowVatItem = dataSetFSO1.VIEW_VAT_IVOICE_ITEM.NewVIEW_VAT_IVOICE_ITEMRow();

                        rowVatItem.VAT_INVOICE_ID = _vatInvRow.ID;
                        rowVatItem.ID = productUnitRow.ID;
                        rowVatItem.CP_STAGE_ID = productUnitRow.CP_STAGE_ID;
                        if (!productUnitRow.IsNSI_PRODUCT_IDNull())
                        {
                            rowVatItem.NSI_PRODUCT_ID = productUnitRow.NSI_PRODUCT_ID;
                        }
                        //значит это работа
                        else
                        {
                            rowVatItem.NSI_PRODUCT_ID = -1;
                            //В базе это значение null поэтому приравниваем к единице
                            //productUnitRow.NSI_PRODUCT_ID = -1;
                        }
                        rowVatItem.PRODUCT_UNIT_NAME = productUnitRow.NAME;
                        rowVatItem.CP_STAGE_END_DATE = productUnitRow.CP_STAGE_END_DATE;
                        rowVatItem.CP_STAGE_NUMBER = productUnitRow.CP_STAGE_NUMBER;
                        rowVatItem.PRODUCT_UNIT_COST = productUnitRow.COST;
                        rowVatItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                        rowVatItem.PAY_PER = productUnitRow.PAY_PER;
                        rowVatItem.NSI_METER_NAME = productUnitRow.NSI_METER_NAME;
                        rowVatItem.NSI_CURRENCY_NAME = productUnitRow.NSI_CURRENCY_NAME;
                        rowVatItem.PRODUCT_UNIT_COST = productUnitRow.COST;
                        rowVatItem.VAT_INVOICE_DATE1 = productUnitRow.VAT_INVOICE_DATE1;
                        rowVatItem.VAT_INVOICE_NUMBER = productUnitRow.VAT_INVOICE_NUMBER;
                        rowVatItem.NSI_PRODUCT_STATE_NAME = productUnitRow.NSI_PRODUCT_STATE_NAME;
						rowVatItem.CALENDAR_PLAN_NUMBER = productUnitRow.CALENDAR_PLAN_NUMBER;
						rowVatItem.INVOICE_OUT_NUMBER = productUnitRow.INVOICE_OUT_NUMBER;
						try
						{
							rowVatItem.PROD_GROUP = productUnitRow.PROD_GROUP;
							rowVatItem.NSI_PROD_GROUP_NAME = productUnitRow.NSI_PROD_GROUP_NAME;
							rowVatItem.N_DRAWING = productUnitRow.N_DRAWING;
						}
						catch
						{ } //группа товара не указана, либо это работы
                        dataSetFSO1.VIEW_VAT_IVOICE_ITEM.AddVIEW_VAT_IVOICE_ITEMRow(rowVatItem);
                    }
                    catch (ConstraintException)
                    {
                        MessageBox.Show("Данный товар уже добавлен к платежу!");
                    }
                }
            }
        }

        private void FormVatInvoice_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (!AllowSave)
				return;
            if (_vatInvRow.RowState != DataRowState.Deleted && _vatInvRow.RowState != DataRowState.Detached && (_vatInvRow.RowState == DataRowState.Added || _vatInvRow.RowState == DataRowState.Modified || (dataSetFSO1.VIEW_VAT_IVOICE_ITEM.GetChanges()) != null || dataSetFSO1.VIEW_VAT_INV_ON_SERVICE.GetChanges() != null))
            {
                DialogResult result = MessageBox.Show(this, "Были внесены изменения. Сохранить?", "Сохранить изменения?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    int SaveResult = this.Save();

                    if (SaveResult == -1)
                    {
                        e.Cancel = true;
                    }
                }
                else if (result == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else
                {
                    dataSetFSO1.RejectChanges();
                }
            }
        }

        private void radCheckBoxIsGuarantyLet_MouseClick(object sender, MouseEventArgs e)
        {
            foreach (DataSetFSO.VIEW_VAT_IVOICE_ITEMRow row in dataSetFSO1.VIEW_VAT_IVOICE_ITEM.Rows)
            {
                if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                {
                    if (row.PAY_PER < 100)
                    {
                        radCheckBoxIsGuarantyLet.Checked = false;
                        return;
                    }
                }
            }
            if (radCheckBoxIsGuarantyLet.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                radTextBoxGLetterDate.Visible = false;
                radTextBoxGLetterDate.Text = "";
                //_vatInvRow.SetGUARANTY_LET_DATENull();
            }
            else if (radCheckBoxIsGuarantyLet.ToggleState == Telerik.WinControls.Enumerations.ToggleState.Off)
            {
                radTextBoxGLetterDate.Visible = true;
                //Перебиндим значение
                //radTextBoxGLetterDate.DataBindings.Clear();
                //radTextBoxGLetterDate.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.GUARANTY_LET_DATEColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged);
            }
            

        }

        private void radLabelContract_DoubleClick(object sender, EventArgs e)
        {
            if (!_vatInvRow.IsPIDNull())
            {
                CONTRACTTableAdapter ta = new CONTRACTTableAdapter();
                FormContract contractForm = new FormContract(ta.GetDataByPID(_vatInvRow.PID).First());
                if (!FormHelper.HasOpenedForm(contractForm.FormName))
                {
                    contractForm.MdiParent = FormHelper.MainForm;
                    contractForm.Show();
                    contractForm.Select();
                }
            }
        }

        private void radLabelOrganization_DoubleClick(object sender, EventArgs e)
        {
            if (_vatInvRow.IsNSI_ORGANIZATION_IDNull())
            {
                DialogFormSelectObject dialog = new DialogFormSelectObject(ObjctTypeEnum.ORGANIZATION);
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    DataSetFSO.NSI_ORGANIZATIONRow org = (DataSetFSO.NSI_ORGANIZATIONRow)dialog.SelectedRow;
                    _vatInvRow.NSI_ORGANIZATION_ID = org.ID;
                    radLabelOrganization.Text = org.SHORT_NAME;
                }
            }
            else
            {
                NSI_ORGANIZATIONTableAdapter ta = new NSI_ORGANIZATIONTableAdapter();
                DataSetFSO.NSI_ORGANIZATIONRow orgRow = ta.GetDataById(_vatInvRow.NSI_ORGANIZATION_ID).FindByID(_vatInvRow.NSI_ORGANIZATION_ID);
                FormNSIOrganization form = new FormNSIOrganization(orgRow);
                if (!FormHelper.HasOpenedForm(form.FormName))
                {
                    form.MdiParent = FormHelper.MainForm;
                    form.Show();
                    form.Select();
                }
            }
        }

        private void radRadioButtonTNN_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            if (args.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                if (_vatInvRow.EXEC_TYPE != (string)_tnnExec.Value)
                    _vatInvRow.EXEC_TYPE = (string)_tnnExec.Value;
            }
        }

        private void radRadioButtonAct_ToggleStateChanged(object sender, StateChangedEventArgs args)
        {
            if (args.ToggleState == Telerik.WinControls.Enumerations.ToggleState.On)
            {
                if (_vatInvRow.EXEC_TYPE != (string)_actExec.Value)
                    _vatInvRow.EXEC_TYPE = (string)_actExec.Value;
            }
        }

        private void radButtonEvaluateSum_Click(object sender, EventArgs e)
        {
            bool isEvaluate = true;
            if (!_vatInvRow.IsSUM_RUBNull() && _vatInvRow.SUM_RUB != 0)
            {
                if (MessageBox.Show("Сумма счет-фактуры может измениться! Пересчитать сумму?", "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                {
                    isEvaluate = false; 
                }
            }

            if (isEvaluate)
            {
                decimal vatSum = 0;
                decimal PUSum;
                decimal? PUSumT;
                
                PRODUCT_UNITTableAdapter ta = new PRODUCT_UNITTableAdapter();
                foreach (DataSetFSO.VIEW_VAT_IVOICE_ITEMRow row in dataSetFSO1.VIEW_VAT_IVOICE_ITEM)
                {
                    PUSum = 0;
                    if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                    {
                        //сумма всех платежей по этому товару              
                        if ((PUSumT = ta.getPUPaySumRub(row.ID)).HasValue)
                        {
                            PUSum = PUSumT.Value;
                        }
                        //Если товар оплачен не полностью, остаток стоимости (в валюте) умножаем на курс валюты на дату счет-фактуры и прибавлям к оплаченной сумме
                        if (row.PAY_PER < 100)
                        {
                            if (PUSum != 0)
                            {
                                PUSum += (row.PRODUCT_UNIT_COST - (decimal)ta.getPUPaySumCur(row.ID)) * FormHelper.GetRate(row.NSI_CURRENCY_NAME, _vatInvRow.DATE);
                            }
                            else
                            {
                                PUSum += row.PRODUCT_UNIT_COST * FormHelper.GetRate(row.NSI_CURRENCY_NAME, _vatInvRow.DATE);
                            }
                        }
                    }

                    vatSum += PUSum;
                }

                _vatInvRow.SUM_RUB = vatSum;

                //Перебиндим значение
                radMaskedEditBoxSum.DataBindings.Clear();
                radMaskedEditBoxSum.DataBindings.Add("Text", _vatInvRow, dataSetFSO1.VAT_INVOICE.SUM_RUBColumn.ColumnName, true, DataSourceUpdateMode.OnPropertyChanged, 0, "N2");
            }
        }

        private void radButtonEvaluateRest_Click(object sender, EventArgs e)
        {
            EvaluateRest();
        }

        private void EvaluateRest()
        { 
            PRODUCT_UNITTableAdapter ta = new PRODUCT_UNITTableAdapter();
            decimal rest = _vatInvRow.SUM_RUB;
            decimal PUSum;
            decimal? PUSumT;
			double PUSumCorrection = 0.0;
            foreach (DataSetFSO.VIEW_VAT_IVOICE_ITEMRow row in dataSetFSO1.VIEW_VAT_IVOICE_ITEM)
            {
                PUSum = 0;
                if (row.RowState != DataRowState.Deleted && row.RowState != DataRowState.Detached)
                {
                    //сумма всех платежей по этому товару              
                    if ((PUSumT = ta.getPUPaySumRub(row.ID)).HasValue)
                    {
                        PUSum = PUSumT.Value;
						//для каждого добавленного товра, добавляем коррекцию на 1 коп
						PUSumCorrection += 0.01;
                    }
                }
                rest -= PUSum;
            }
			if (double.Parse(rest.ToString()) < PUSumCorrection)
				rest = 0;
            radLabelVatInvRest.Text = String.Format("{0:N2} Руб.", rest);
        }

        private void radMenuItemAddFromPayIn_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectInvOutDialog = new DialogFormSelectObject(ObjctTypeEnum.PAYMENT_IN, _vatInvRow.PID);
            DataSetFSO.PAYMENT_INRow payIn;
            if (selectInvOutDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (payIn = selectInvOutDialog.SelectedRow as DataSetFSO.PAYMENT_INRow) != null)
            {
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _vatInvRow.PID);
                (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridByPayInIDForVatInvoice(payIn.ID, _vatInvRow.IS_GUARANTY_LET);

                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }

            }
        }

        private void radMenuItemAddFromInvOut_Click(object sender, EventArgs e)
        {
            DialogFormSelectObject selectInvOutDialog = new DialogFormSelectObject(ObjctTypeEnum.INVOICE_OUT, _vatInvRow.PID);
            DataSetFSO.INVOICE_OUTRow invOut;
            if (selectInvOutDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (invOut = selectInvOutDialog.SelectedRow as DataSetFSO.INVOICE_OUTRow) != null)
            {
                DialogFormSelectObject selectPUDialog = new DialogFormSelectObject(ObjctTypeEnum.PRUDUCT_UNIT_FOR_FORMS, _vatInvRow.PID);
                (selectPUDialog.Control as UserControlSearchPrUnitByID).FillGridByInvoiceOutIDForVatInvoice(invOut.ID, _vatInvRow.IS_GUARANTY_LET);

                if (selectPUDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    AddPUFromSelectDialog(selectPUDialog);
                }

            }
        }

        private void radButtonDeleteProducts_Click(object sender, EventArgs e)
        {
            //GridViewRowInfo rowInf = radGridViewItems.SelectedRows.FirstOrDefault();
            if (_vatInvRow.TYPE == (string)_productType.Value)
            {
                DataSetFSO.VIEW_VAT_IVOICE_ITEMRow tmpPURow;
                foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
                {
                    if ((tmpPURow = (rowInf.DataBoundItem as DataRowView).Row as DataSetFSO.VIEW_VAT_IVOICE_ITEMRow) != null)
                    {
                        int nsiProdId = tmpPURow.NSI_PRODUCT_ID;
                        DataSetFSO.AGGR_PRODUCT_UNTSRow aggrPURow = (from aggrRow in dataSetFSO1.AGGR_PRODUCT_UNTS where (aggrRow.NSI_PRODUCT_ID == nsiProdId) select aggrRow).First();
                        aggrPURow.COUNT--;
                        rowInf.Delete();
                    }
                }
            }
            else if (_vatInvRow.TYPE == (string)_serviceType.Value)
            {
                foreach (GridViewRowInfo rowInf in radGridViewItems.SelectedRows.ToList())
                {
                    rowInf.Delete();
                }
            }
        }

        private void radButtonDeleteOrg_Click(object sender, EventArgs e)
        {
            _vatInvRow.SetNSI_ORGANIZATION_IDNull();
            radLabelOrganization.Text = "<Не указана>";
        }
    }
}
